package com.oa.modules.approvalsec1.service.impl;

import cn.hutool.core.io.FileUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfWriter;
import com.oa.common.utils.*;
import com.oa.modules.approvalsec1.controller.WxLoginController;
import com.oa.modules.approvalsec1.entity.RoomStoreEntity;
import com.oa.modules.approvalsec1.service.RoomStoreService;
import com.oa.modules.approvalsec1.socket.WebSocketServer;
import com.oa.modules.approvalsec1.wx.HttpUtils;
import com.oa.modules.sys.entity.SysUserEntity;
import com.oa.modules.sys.service.SysUserService;
import lombok.extern.log4j.Log4j2;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.io.*;
import java.util.Map;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.oa.modules.approvalsec1.dao.ExplorationCloudDao;
import com.oa.modules.approvalsec1.entity.ExplorationCloudEntity;
import com.oa.modules.approvalsec1.service.ExplorationCloudService;


@Service("explorationCloudService")
@Log4j2
public class ExplorationCloudServiceImpl extends ServiceImpl<ExplorationCloudDao, ExplorationCloudEntity> implements ExplorationCloudService {

    @Autowired
    private PdfUtil pdfUtil;

    @Autowired
    private RoomStoreService roomStoreService;

    @Autowired
    private SysUserService sysUserService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        params.put("status", Constant.YES_OR_NO.YES.getValue());
        IPage page = AppUtils.getPage(new Query<ExplorationCloudEntity>(), params);
        return AppUtils.setPage(page, baseMapper.findPage(params), baseMapper.findRecords(page, params));
    }

    @Override
    public ExplorationCloudEntity queryForRoomNum(String roomNum) {
        return baseMapper.queryForRoomNum(roomNum);
    }

    @Override
    public PageUtils findHistory(Map<String, Object> params) {
        params.put("status", Constant.YES_OR_NO.YES.getValue());
        IPage page = AppUtils.getPage(new Query<ExplorationCloudEntity>(), params);
        return AppUtils.setPage(page, baseMapper.findHistoryCount(params), baseMapper.findHistory(page, params));
    }

    /**
     * 将上传的docx格式文档转成pdf格式
     *
     * @param paths
     * @return
     */
    @Override
    public String toPdf(String paths) {
        String[] ps = paths.split(",");
        StringBuilder pdfPaths = new StringBuilder();
        for (String p : ps) {
            String path = p.replaceAll("https://www.qhspj.com/", "/home/file");
            String prefix = path.replace(".docx", ".pdf").replace(".doc", ".pdf").replace("xls", "pdf").replace(".xlsx", ".xls");
            File file = new File(prefix);
            if (!file.exists()) {
                FileUtil.touch(file);
            }
            if(path.indexOf(".doc")!=-1||path.indexOf(".docx")!=-1){
                PdfUtil.docToPdf(path, prefix);
            }else{
                PdfUtil.xlsToPdf(path, prefix);
            }
            String result = prefix.replaceAll("/home/file", "https://www.qhspj.com/");
            pdfPaths.append(result + ",");
        }
        return pdfPaths.deleteCharAt(pdfPaths.length() - 1).toString();
    }

    /**
     * 签名
     *
     * @param params
     */
    @Override
    public String signature(Map<String, Object> params) {
        String id = (String) params.get("id");
        Map<String, String> files = (Map<String, String>) params.get("files");
        //存储签名之后的地址
        StringBuilder builder = new StringBuilder();
        if (files != null) {
            String target = files.get("target");
            String sign = files.get("sign");
            //未签名的pdf地址
            String pdfPath = target.replaceAll("https://www.qhspj.com//examination-approval-project", "/home/file/examination-approval-project");
            //签名图片地址
            String signature = sign.replaceAll("https://www.qhspj.com//examination-approval-project", "/home/image/examination-approval-project");
            //添加签名水印
            try {
                //签名后的文件地址
                String signPdfPath = pdfUtil.getCoordInfo(pdfPath, signature);
                log.error("签名完成---- \n 签名后的文件地址：{}", signPdfPath);
                //签名成功之后将签名之后的pdf地址存到builder
                String sp = signPdfPath.replaceAll("/home/file/examination-approval-project", "https://www.qhspj.com//examination-approval-project");
                builder.append(sp);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (builder != null && builder.length() > 0) {
            ExplorationCloudEntity cloudEntity = baseMapper.selectOne(new QueryWrapper<ExplorationCloudEntity>().eq("room_num", id));
            if (cloudEntity.getSignPath() != null && !"".equals(cloudEntity.getSignPath())) {
                cloudEntity.setSignPath(cloudEntity.getSignPath() + "," + builder);
            } else {
                cloudEntity.setSignPath(builder.toString());
            }
            baseMapper.updateById(cloudEntity);
            RoomStoreEntity roomStore = roomStoreService.getOne(new LambdaQueryWrapper<RoomStoreEntity>().eq(RoomStoreEntity::getRoomNum, id));
            //发送给已签名的文件到后台
            WebSocketServer.sendMessage3(roomStore.getUserId(), builder.toString());
            return builder.toString();
        }
        return "";
    }

    @Override
    public void sendFile(ExplorationCloudEntity cloudEntity) {
        //获取房间信息
        RoomStoreEntity roomStore = roomStoreService.getOne(new QueryWrapper<RoomStoreEntity>().eq("room_num", cloudEntity.getRoomNum()));
        String userId = roomStore.getPushId();
        SysUserEntity sysUser = sysUserService.getById(userId);
        if (sysUser != null) {
            String openId = sysUser.getWxOpenId();
            JSONObject xmlData = new JSONObject();
            String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + WxLoginController.getAccessToken();
            xmlData.put("touser", openId);//用户的openid（要发送给那个用户，通常这里应该动态传进来的）
            xmlData.put("template_id", "6I5x9ivwUDgFQo7xntnOOZHy3Bp_vJRyty0QERsPO9w");//订阅消息模板id
            xmlData.put("miniprogramState", "developer");
            xmlData.put("page", "pages/historyApplyInfo/historyApplyInfo?id="+cloudEntity.getId());

            JSONObject data = new JSONObject();
            JSONObject thing1 = new JSONObject();
            thing1.put("value", "现场核查表");
            data.put("thing1", thing1);

            JSONObject thing4 = new JSONObject();
            thing4.put("value", "请点击小程序查阅");
            data.put("thing4", thing4);

            xmlData.put("data", data);
            String result = HttpUtils.post(url, xmlData.toString());
            System.out.println(result);
        }
    }





    @Override
    public void test() {
        String openId = "o8bfw4l0Ayd0V5rEfzWWxqvDGYFg";
        JSONObject xmlData = new JSONObject();
        String url = "https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token=" + WxLoginController.getAccessToken();
        xmlData.put("touser", openId);//用户的openid（要发送给那个用户，通常这里应该动态传进来的）
        xmlData.put("template_id", "6I5x9ivwUDgFQo7xntnOOZHy3Bp_vJRyty0QERsPO9w");//订阅消息模板id
        xmlData.put("miniprogramState", "developer");
        xmlData.put("page", "pages/historyApply/historyApply?id=08b8559f56b54cccbf50e4897a4b0aa3");

        JSONObject data = new JSONObject();
        JSONObject thing1 = new JSONObject();
        thing1.put("value", "现场核查表");
        data.put("thing1", thing1);

        JSONObject thing4 = new JSONObject();
        thing4.put("value", "请点击小程序查阅");
        data.put("thing4", thing4);

        xmlData.put("data", data);
        String result = HttpUtils.post(url, xmlData.toString());
        System.out.println(result);
    }







}
